#!/bin/bash

#/*
#* 
#* Copyright 2013 Kamil Cukrowski <kamil@dyzio.pl>
#* 
# * ----------------------------------------------------------------------------
#* "THE BEER-WARE LICENSE" (Revision 42):
#* Kamil Cukrowski <kamil@dyzio.pl> wrote this file. As long as you retain this notice you
#* can do whatever you want with this stuff. If we meet some day, and you think
#* this stuff is worth it, you can buy me a beer in return.
#* ----------------------------------------------------------------------------
#*/

# power settings script
# created to control all devices in my laptop

function check_running {
	test $(ps x | grep "$1" | wc -l | tr '\n' ' ') == "2" && echo 1 ||  echo 0
}
function check_module {
	lsmod | grep "$1" >/dev/null && echo 1 || echo 0
}
function systemctl_wrapper {
case $1 in
"start")
	systemctl start $2
;;
"stop") 
	systemctl stop $2
;;
*)
	systemctl status $2 -n1 | grep "Active: active" >/dev/null && echo 1 || echo 0
;;
esac
}

services=""
file=/home/kamil/Documents/fujitsu/psscript-services.sh
#a=$(typeset -F) ## remember all declared functions.
test -f $file && . $file || ( echo STRICTP  NOT FOUND; exit -1; )
#b=$(typeset -F)
#services=$( diff <(echo "$a") <(echo "$b") | grep "declare -f" | sed 's/> declare -f //' | tr '\n' ' ')
#echo $services; exit

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root." 
   exit -1
fi

_ME=$0
_OPT=$1
shift
case $_OPT in
"check")
	what=" $@ "
	test -z "$2" && what=" $services "
	for i in $what; do
		echo $i check = $($i check)
	done
	;;
"checkshort")
	$1 check
	;;
"start")
	if [[ -z "$@" ]]; then echo What services to start?; exit; fi
	for i in $@; do
		if test "$($i check)" -eq 1; then echo $i is already running.; continue; fi
		echo $i start
		$i start > /tmp/.psscript.$i 2>/tmp/.psscript.$i
		echo -e "\t\t\t\tDONE"
	done
	;; 
"stop")
	if [[ -z "$@" ]]; then echo What services to stop?; exit; fi
	for i in $@; do
		if test "$($i check)" -eq 0; then echo $i not running.; continue; fi
		echo $i stop
		$i stop
		echo -e "\t\t\t\tDONE"
	done
	;;
"restart")
	$_ME stop  $@
	$_ME start $@
	;;
"show")
	# LEAVE THIS ALONE FOR main.c SAKE
	echo services: 	$services
	;;
"info" | "--help" | "-h" | *)
	echo USAGE: $0 [option] [what_services]
	echo $_ME start -- wszystkie serwisy startuje
	echo $_ME stop -- stopuje wszystkie servisy
	echo $_ME restart -- stopuje wszystkie servisy
	echo $_ME check -- stopuje wszystkie servisy
	echo Available services: $services
	;;
esac

